<template>
  <div class='user-profile-page'>
    <!-- 导航 -->
    <van-nav-bar left-arrow @click-left="$router.back()" title="个人信息"></van-nav-bar>
    <!-- 单元格 -->
    <van-cell-group>
      <!-- islink 点击效果 title左侧标题 value内容 -->
      <van-cell is-link title="头像" center @click="showPhoto=true">
        <van-image
          slot="default"
          fit="cover"
          round
          :src="user.photo"
        />
      </van-cell>
      <van-cell is-link title="昵称" :value="user.name" @click="openNamePopup " />
    </van-cell-group>
    <van-cell-group style="margin-top:12px">
      <van-cell is-link title="性别" @click="showGender=true" :value="user.gender===0?'男':'女'" />
      <van-cell is-link title="生日"  @click="showBirthdayPopup" :value="user.birthday||'未填写'" />
    </van-cell-group>
    <div class="logout">
      <span @click="loginout">退出登录</span>
    </div>
    <!-- 修改头像动作面板 -->
    <van-action-sheet
      v-model="showPhoto"
      :actions="[{name:'拍照',value:0},{name:'本地选择',value:1}]"
      cancel-text="取消"
      @select="onPhotoSelect"
    />
    <input @change="updatePhoto" type="file" ref="file" style="display:none">
    <!-- 修改昵称 弹出层 -->
    <van-popup class="my-popup"  v-model="showName"  position="right">
      <!-- 导航栏 -->
      <van-nav-bar
        title="修改昵称"
        right-text="保存"
        left-arrow
        @click-left="showName=false"
        @click-right="saveName"
        />
        <van-field v-model="name" />
    </van-popup>
    <!-- 修改性别 -->
     <van-action-sheet
       v-model="showGender"
       :actions="[{name:'男',value:0},{name:'女',value:1}]"
       cancel-text="取消"
       @select="onGenderSelect"
     />
   <!-- 修改生日 -->
     <van-popup v-model="showBirthday" position="bottom">
       <van-datetime-picker
        v-model="birthday"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showBirthday=false"
        @confirm="saveBirthday"
     />
     </van-popup>
  </div>
</template>
<script>
import { getUserProfile, updateUserPhoto, updateUserProfile } from '@/api/user'
import dayjs from 'dayjs'
export default {
  name: 'UserProfilePage',
  data () {
    return {
      user: {},
      showPhoto: false,
      showName: false,
      name: '',
      showGender: false,
      showBirthday: false,
      birthday: new Date(),
      minDate: new Date('1960-01-01'),
      maxDate: new Date()
    }
  },
  created () {
    this.getUserProfile()
  },
  methods: {
    // 修改日期
    async saveBirthday () {
      // 获取到当前时间
      // 发送请求,新时间赋值给旧时间,关闭对话框,成功提示
      const str = dayjs(this.birthday).format('YYYY-MM-DD')
      const [err] = await updateUserProfile({ birthday: str })
      if (err) return this.$toast.fail('修改生日失败')
      this.user.birthday = str
      this.showBirthday = false
      this.$toast.success('修改生日成功')
    },
    // 打开日期选择器
    showBirthdayPopup () {
      this.showBirthday = true
      this.birthday = new Date(this.user.birthday)
    },
    // 点击性别,修改性别事件
    async onGenderSelect (action) {
      // 发送请求,修改性别,重新赋值性别,关闭弹出层
      const [err] = await updateUserProfile({ gender: action.value })
      if (err) return this.$toast.fail('修改性别失败')
      this.user.gender = action.value
      this.showGender = false
      this.$toast.success('修改性别成功')
    },
    // 点击保存,保存修改后的昵称
    async saveName () {
      // 校验name是否为空
      // 发送请求
      // 获取到最新的name,赋值给user.name,关闭弹窗,提示修改成功,name为空
      if (!this.name) return this.$toast('请输入昵称')
      const [err] = await updateUserProfile({ name: this.name })
      if (err) return this.$toast.fail('修改昵称失败')
      this.user.name = this.name
      this.showName = false
      this.$toast.success('修改昵称成功')
    },
    // 点击昵称弹出层事件
    openNamePopup () {
      this.showName = true
      this.name = this.user.name
    },
    // 上传修改的头像事件
    async updatePhoto () {
      // 拿到选中的图片
      const file = this.$refs.file.files[0]
      // 选中图片后,再进行发送请求
      if (file) {
        // 封装成一个formDat对象
        const fromData = new FormData()
        fromData.append('photo', file)
        // console.log(fromData)
        // 发送请求
        const [err, res] = await updateUserPhoto(fromData)
        if (err) return this.$toast.fail('修改头像失败')
        // console.log(res)
        this.user.photo = res.data.data.photo
        this.$toast.success('修改头像成功')
      }
    },
    // 确定点击的是本地,然后打开资源管理器
    onPhotoSelect (action) {
      if (action.value === 1) {
        // 点击的是本地,触发input的change事件
        this.$refs.file.click()
        // 关闭活动面板
        this.showPhoto = false
      }
    },
    // 获取用户信息用于编辑资料
    async getUserProfile () {
      const [, res] = await getUserProfile()
      // console.log(res.data.data)
      this.user = res.data.data
    },
    // 退出登陆
    loginout () {
      this.$dialog.confirm({
        title: '温馨提示',
        message: '确认退出极客园吗?'
      })
        .then(() => {
          this.$store.commit('user/setToken', '')
          this.$router.push('/')
        })
        .catch(() => {})
    }
  }
}
</script>
<style lang="less" scoped>
.my-popup{
  width: 100%;
  height: 100%;
  /deep/ .van-nav-bar__text{
    color: #999;
  }
  /deep/ .van-field__control{
    background: @geek-gray-color;
    padding: 10px;
    border-radius: 4px;
  }
}
.user-profile-page {
  background: #f8f8f8;
  .van-image {
    display: block;
    float: right;
    width: 30px;
    height: 30px;
  }
  .van-cell__title {
    width: 50px;
    flex: none;
  }
}
.logout {
  text-align: center;
  position: absolute;
  left: 0;
  bottom: 30px;
  width: 100%;
  color: @geek-color;
}
</style>
